import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/index.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/index.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/',
      component: Layout,
      redirect: '/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/dashboard/index.vue'),
          meta: { title: '能源看板', requiresAuth: true }
        },
        {
          path: 'energy',
          name: 'Energy',
          redirect: '/energy/collect',
          meta: { title: '煤能耗', requiresAuth: true },
          children: [
            {
              path: 'collect',
              name: 'EnergyCollect',
              component: () => import('@/views/energy/collect/index.vue'),
              meta: { title: '采集点数据' }
            },
            {
              path: 'device',
              name: 'EnergyDevice',
              component: () => import('@/views/energy/device/index.vue'),
              meta: { title: '仪表管理' }
            }
          ]
        },
        {
          path: 'history',
          name: 'History',
          component: () => import('@/views/history/index.vue'),
          meta: { title: '历史数据', requiresAuth: true }
        },
        {
          path: 'daily',
          name: 'Daily',
          component: () => import('@/views/daily/index.vue'),
          meta: { title: '日数据', requiresAuth: true }
        },
        {
          path: 'monthly',
          name: 'Monthly',
          component: () => import('@/views/monthly/index.vue'),
          meta: { title: '月数据', requiresAuth: true }
        },
        {
          path: 'system',
          name: 'System',
          component: () => import('@/views/system/index.vue'),
          meta: { title: '系统配置', requiresAuth: true }
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    },
    {
      path: '/404',
      name: '404',
      component: () => import('@/views/error/404.vue'),
      meta: { title: '404' }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置标题
  document.title = `${to.meta.title} - 能耗托线监测系统`
  
  // 检查是否需要登录认证
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token')
    if (!token) {
      next('/login')
      return
    }
  }
  
  next()
})

export default router
